package com.korion.test

import android.os.AsyncTask
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.Window
import android.view.WindowManager
import android.widget.ArrayAdapter
import com.instacart.library.truetime.TrueTime
import kotlinx.android.synthetic.main.activity_main.*
import java.io.IOException
import java.sql.Time
import java.util.*
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "MainActivity"
    }

    private val list = mutableListOf<TimeCut>()
    private var running: Boolean = false
    private var cut: Boolean = false
    private val handler = Handler()
    private var trueTimeInitTask: AsyncTask<Void, Void, Boolean>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(R.layout.activity_main)
        btn_print.setOnClickListener {
            if (!running && trueTimeInitTask?.get() == true){
                running = true
                btn_print.setText(R.string.stop)
                handler.post(object : Runnable {
                    override fun run() {
                        if (running){
                            val localTime = Date().time
                            val trueTime = TrueTime.now().time
                            if (cut){
                                cutThisTime(localTime, trueTime)
                                cut = false
                            }
                            tv_local_time.text = localTime.toString()
                            tv_true_time.text = trueTime.toString()
                            handler.post(this)
                        }
                    }
                })
                statisticalMeanDifference()
            } else {
                running = false
                btn_print.setText(R.string.start)
            }
        }

        btn_cut.setOnClickListener {
            cut = true
        }

        btn_clear.setOnClickListener {
            list.clear()
            (time_list.adapter as ArrayAdapter<TimeCut>).notifyDataSetChanged()
        }
        trueTimeInitTask = TrueTimeTask()
        trueTimeInitTask?.execute()
        time_list.adapter = ArrayAdapter<TimeCut>(this, R.layout.list_item, R.id.tv_tip, list)
    }

    private fun cutThisTime(localTime: Long, trueTime: Long) {
        val timeCut = TimeCut(localTime, trueTime)
        list.add(timeCut)
        (time_list.adapter as ArrayAdapter<TimeCut>).notifyDataSetChanged()
    }

    private fun statisticalMeanDifference(){
        thread {
            var sum = 0L
            var count = 0
            while (count <= 100){
                val local = Date().time
                val trueTime = TrueTime.now().time
                val absDiff = Math.abs(local - trueTime)
                sum += absDiff * absDiff
                Thread.sleep(50)
                count++
            }
            val result = Math.sqrt(sum*1.0/count)
            handler.post {
                tv_tip_bar.text = String.format("Average Diff: %.2f", result)
            }
        }
    }

}

class TrueTimeTask: AsyncTask<Void, Void, Boolean>(){

    companion object {
        private const val TAG = "TrueTimeTask"
    }

    override fun doInBackground(vararg params: Void?): Boolean {
        try {
            TrueTime.build().initialize()
        } catch (e: IOException){
            Log.d(TAG, "TrueTime init fail")
            return false
        }
        val date = TrueTime.now()
        Log.d(TAG, "TrueTime init success:$date")
        return true
    }
}

data class TimeCut(
    val localTime: Long,
    val trueTime: Long
){
    override fun toString(): String {
        return "local: $localTime, true: $trueTime,  diff: ${trueTime - localTime}"
    }
}
